//-- Namespace --
if (typeof wildpack === 'undefined') { wildpack = {}; }

wildpack.SimpleDatexS = new Class({
    Implements: [Events, Options],

    //-- Constructor --
    initialize: function() {
        this._target = '';
        this._class = '';
        this._stateid = '';
        this._isNew = true;
        this.Data = [];
        this.Loaded = false;
    },
    
    //-- The callback for all request (synchro of data) --
    _baseCb: function(d, t) {
    	this.Data = d.data;
        this.Loaded = d.loaded;
        this._isNew = d._isNew;
        this._stateid = d.stateid;
        
        if (d.error !== '') {
        	this.fireEvent('error', d.error);
        	return false;
        }
        
        return true;
    },
    
    //-- Performs the request --
    _doReq: function(method, param, cb)
    {
    	var jr = new Request.JSON({
            url: this._target,
            onSuccess: function(d, t) {
	        	var chk = this._baseCb(d, t);
	            if(typeof cb === 'function') {
	                cb.run([this, d.returnvalue, chk]);
	            }
            }.bind(this)
        });
        jr.get({
            cls: this._class,
            method: method,
            param: param,
            stateid: this._stateid
        });
    },
    
    /**
     * Retrieves the value of the field specified by name
     */
    get: function(field) {
        if (this.Loaded !== true) {
            return null;
        }
        return this.Data[field];
    },
    
    /**
     * Loads a dataset using the specified condition
     * @param {Object} condition An object containing fieldnames and values used to select the dataset 
     */
    load: function(condition, cb) {
        var p = JSON.encode([condition]);
        this._doReq('load', p, cb);
    },

    /**
     * Set several fields with one call
     * @param {Object} data The field values to set
     */
    qset: function(data, cb) {
        var p = JSON.encode([data]);
        this._doReq('qset', p, cb);
    },

    /**
     * Permanently deletes either the currently loaded dataset or a dataset specified by key
     * @param {Object} key The key of the dataset to delete
     */
    remove: function(key, cb) {
    	this._doReq('remove', key, cb);
    },

    /**
     * Save the currently loaded dataset
     */
    save: function(cb) {
    	this._doReq('save', '', cb);
    },
    
    /**
     * Update dataset without loading it before. The data object must contain the key which is used 
     * to identify the dataset to update.
     * @param {Object} data The fieldvalues to update
     */
    update: function(data, cb) {
        var p = JSON.encode([data]);
        this._doReq('update', p, cb);
    }
});
